package kargo.suratkargokargotakip;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.graphics.Color;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class FillTableLayoutFromWebService {
	public static void RequestXml(final Spinner spinner,final Activity screen,
			final TableLayout tableLayout, String url, String methodName,
			HashMap<String, String> parameters, final String startTagName,
			final Boolean firstLevel) {
		String envelope = "<?xml version=\"1.0\" encoding=\"iso-8859-9\"?>"
				+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" "
				+ "soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">"
				+ "<soap:Body>";
		envelope += "<" + methodName + " xmlns=\"http://tempuri.org/\">";

		if (parameters != null) {
			for (HashMap.Entry<String, String> entry : parameters.entrySet()) {
				envelope += "<" + entry.getKey() + ">" + entry.getValue()
						+ "</" + entry.getKey() + ">";
			}
		}
		envelope += "</" + methodName + ">";
		envelope += "</soap:Body>" + "</soap:Envelope>";
		// String url = "http://webservices.suratkargo.com.tr/services.asmx";
		String soapAction = "http://tempuri.org/" + methodName;

		final CallWebService webService = new CallWebService(screen);

		webService.RunCode = new Runnable() {
			@Override
			public void run() {
				try {
					FillArray(spinner,screen, tableLayout, webService.ResponseString,startTagName, firstLevel);
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		};

		try {
			webService.execute(url, soapAction, envelope);
		} catch (Exception e) {
		}
	}
	
	

	String str = null;

	private static void FillArray(Spinner spinner,final Activity screen,
			final TableLayout tableLayout, String str, String startTagName,
			Boolean firstLevel) throws ParserConfigurationException,
			SAXException, IOException {
		ArrayList<HashMap<String, String>> array = null;
		if (str != null) {

			String sMethodBaslangic = "";
			if (firstLevel)
				sMethodBaslangic = "<" + startTagName + ">";
			else
				sMethodBaslangic = "<" + startTagName + " xmlns=\"\">";
			String sMethodBitis = "</" + startTagName + ">";
			int artiBaslangic = sMethodBaslangic.indexOf(">");
			artiBaslangic++;
			int baslangic = str.indexOf(sMethodBaslangic);
			baslangic += artiBaslangic;
			str = str.substring(baslangic);
			int bitis = str.indexOf(sMethodBitis);
			str = str.substring(0, bitis);
			str = str + sMethodBitis;
			str = new StringBuffer(str).insert(0, "<" + startTagName + ">")
					.toString();

			byte[] bytes = str.getBytes();
			ByteArrayInputStream bInputStream = new ByteArrayInputStream(bytes);

			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			org.w3c.dom.Document doc = docBuilder.parse(bInputStream);
			org.w3c.dom.Element element = doc.getDocumentElement();
			NodeList nl = element.getChildNodes();
			int rowIndex = nl.getLength();
			array = new ArrayList<HashMap<String, String>>();

			if (firstLevel) {
				array.add(new HashMap<String, String>());
				for (int j = 0; j < rowIndex; j++) {
					Node node = nl.item(j);
					if (node.getLastChild() != null)
						array.get(0).put(node.getNodeName(),
								node.getLastChild().getNodeValue());
				}
			} else {

				for (int i = 0; i < rowIndex; i++) {
					NodeList nlChildren = nl.item(i).getChildNodes();
					array.add(new HashMap<String, String>());
					for (int j = 0; j < nlChildren.getLength(); j++) {
						Node node = nlChildren.item(j);
						if (node.getChildNodes().item(0) != null)
							array.get(i).put(
									node.getNodeName(),
									(node.getChildNodes().item(0)
											.getNodeValue()));
					}

				}
			}
			
			
			
		}
		if(spinner!=null)
		{
		String[] paths=new String[array.size()];
		
		
		for (int i = 0; i < array.size(); i++) {

			HashMap<String, String> d = (HashMap<String, String>) array.get(i);
			int a = 0;
			for (HashMap.Entry<String, String> entry : d.entrySet()) {
				a++;
				if(a==2)
				paths[i]= entry.getValue();
			}
		}
		ArrayAdapter<String> adapter= new ArrayAdapter<String>(screen,android.R.layout.simple_spinner_item,paths);

		spinner.setAdapter(adapter);
		}
		else
			FillTableLayout(screen, tableLayout, array);
	}
	
	private static void FillTableLayout(Activity screen,
			TableLayout tableLayout, ArrayList<HashMap<String, String>> array) {
		// TableLayout tableLayout = (TableLayout)
		// findViewById(R.id.tableLayout1);
		tableLayout.removeAllViewsInLayout();
		tableLayout.invalidate();

		for (int i = 0; i < array.size(); i++) {

			HashMap<String, String> d = (HashMap<String, String>) array.get(i);
			int a = 0;
			for (HashMap.Entry<String, String> entry : d.entrySet()) {
				a++;
				TableRow row = new TableRow(screen);
				row.setBackgroundColor(Color.BLACK);
				if (a == 1)
					row.setPadding(2, 2, 2, 2); // Border between rows
				else
					row.setPadding(2, 0, 2, 2); // Border between rows

				TableRow.LayoutParams llp = new TableRow.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				llp.setMargins(0, 0, 2, 0);// 2px right-margin

				// New Cell
				LinearLayout cell = new LinearLayout(screen);
				cell.setBackgroundColor(Color.WHITE);
				cell.setLayoutParams(llp);// 2px border on the right for the
											// cell

				// Create a TextView to house the name of the province TextView
				TextView labelTV = new TextView(screen);
				labelTV.setPadding(0, 0, 4, 3);
				cell.addView(labelTV);
				labelTV.setText(entry.getKey());
				row.addView(cell);

				// New Cell
				LinearLayout cell2 = new LinearLayout(screen);
				cell2.setBackgroundColor(Color.WHITE);
				cell2.setLayoutParams(llp);// 2px border on the right for the
											// cell
				TextView valueTV = new TextView(screen);
				valueTV.setPadding(0, 0, 4, 3);
				cell2.addView(valueTV);
				valueTV.setText(entry.getValue());

				row.addView(cell2);

				tableLayout.addView(row);

			}

		}
	}
	
	
}
